# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.conf import settings
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from users.models import User
from users.serializers import UserSerializers, UserDetailSerializer, UserEmailSerializer
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
import base64, pickle
from django_redis import get_redis_connection


class UserNameCountView(APIView):

    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        return Response(
            {
                'count': count
            }
        )


class MobileCountView(APIView):

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        return Response(
            {
                'count': count
            }
        )


class UserView(CreateAPIView):
    # 用户注册
    serializer_class = UserSerializers

    # 重写post方法添加用户注册后合并购物车的逻辑
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        response = Response(serializer.data)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, user, response)

        return response

# class UserDetailView(APIView):
#
#     def get(self, request):
#
#         # 获取用户对象
#         user = request.user
#
#         # 序列化返回
#         ser = UserDetailSerializer(user)
#
#         return Response(ser.data)


class UserDetailView(RetrieveAPIView):

    serializer_class = UserDetailSerializer

    def get_object(self):

        return self.request.user


class UserEmailView(UpdateAPIView):
    '''保存用户邮箱'''
    # queryset =
    serializer_class = UserEmailSerializer

    def get_object(self):
        # 重写方法，指定返回的结果内容

        return self.request.user


class EmailVerifyView(GenericAPIView):
    '''验证邮箱'''
    def get(self, request):
        # 获取前端数据
        data = request.query_params.get('token')
        if not data:
            return Response({'errors': '缺少token'}, status=400)

        # 进行解密
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(data)
        except BaseException:
            return Response({'errors': '无效的token'}, status=400)

        username = data.get('username')

        # 查询用户
        user = User.objects.get(username=username)
        # 邮箱状态更新
        user.email_active = True
        user.save()

        ser = UserDetailSerializer(user)

        return Response(ser.data)


class UserLoginView(ObtainJSONWebToken):

    def post(self, request, *args, **kwargs):
        '''合并购物车'''
        # 调用父类原有的登录业务逻辑实现用户登录
        response = super().post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 获取user对象
            user = serializer.object.get('user') or request.user

            response = merge_cart_cookie_to_redis(request, user, response)

        return response